/**
 * Created by zhangligang
 * Email: tzhang2450@163.com
 * Date: 2019/1/19
 * Time: 23:41
 */
$(function () {
    $('.rule-role').on('change', function () {
        $('.rule-department-name').val('');
        if ($(this).val() == 2) {
            $('.rule-department-name').parents('.form-group').removeClass('hidden');
        } else {
            $('.rule-department-name').parents('.form-group').addClass('hidden');
        }
    });

    $('.btn-save').on('click', function(){
        var data = {
            realname: $('.rule-realname').val(),
            username: $('.rule-username').val(),
            password: $('.rule-password').val(),
            department_name: $('.rule-department-name').val(),
            role: $('.rule-role').val()
        };

        if (checkForm(data)) {
            checkUserName(data);
        }
    });
});

function checkForm(data) {
    if (data.realname == '') {
        alertTip('姓名不能为空');
        return false;
    }
    if (data.username == '') {
        alertTip('账号不能为空');
        return false;
    }
    if (data.password == '') {
        alertTip('密码不能为空');
        return false;
    }
    if (data.role == '') {
        alertTip('请选择角色');
        return false;
    }
    if (data.role == 2 && data.department_name == '') {
        alertTip('党支部名称不能为空');
        return false;
    }
    return true;
}

function checkUserName(data) {
    sendAjax('/v1/manager/check/user/name.json', 'get', {username: data.username}, function (json) {
       if (json.body.repeat == 1) {
           swal({
               title:"糟糕",
               text:'账号已存在',
               type:"error"
           });
       } else {
           saveData('/v1/manager/save/manager', {params:data}, '/manager/rule.html');
       }
    });
}